<template>
  <div class="bind-poster-page">
    <divider v-if="loginUser.is_team_manager">选择绑定类型</divider>
    <checker v-if="loginUser.is_team_manager"
      v-model="isTeam"
      default-item-class="isteam-item"
      selected-item-class="isteam-item-selected"
      >
      <checker-item value="0">个人</checker-item>
      <checker-item value="1">团队</checker-item>
    </checker>
    <group>
      <x-input @on-change="isValid()" :class="{'weui-cell_warn': errors.poster_name }" title="海报名称" v-model="poster.poster_name" placeholder-align="right" placeholder="请输入海报名字">
      </x-input>
      <x-input @on-change="isValid()" :class="{'weui-cell_warn': errors.poster_id }" title="海报ID" v-model="poster.poster_id" placeholder-align="right" placeholder="海报ID"></x-input>
      <selector v-if="isTeam === '1' && loginUser.is_team_manager" direction="rtl" title="所属团队" v-model="poster.team_id" :options="myTeamList" placeholder-align="right" placeholder="选择团队"></selector>
    </group>
    <div class="error-wrapper" v-if="Object.keys(errors).length">
      <div v-if="errors.poster_name" class="weui-cell_warn">{{errors.poster_name}}</div>
      <div v-if="errors.poster_id" class="weui-cell_warn">{{errors.poster_id}}</div>
    </div>
    <div class="pointer-tips">
      <p>步骤指引：</p>
      <p>1.微信关注企业开通的微信服务号</p>
      <p>2.在公众号回复关键字（由企业的运营人员提供）</p>
      <p>3.获取到海报ID和海报名称</p>
      <p>4.打开钉钉应用在该页面填写</p>
      <p>5.成功绑定海报</p>
      <p>6.没有开通公众号请先到微信平台开通后再使用</p>
      <p>7.海报绑定类型选择个人，客户扫码后名单进入顾问个人名下；绑定类型选择团队，客户扫码后名单按照团队设置的规则分配；</p>
    </div>
    <!-- <span class="btn scrm-default-btn bind-post-btn" @click="saveBindPoster">保存</span> -->
    <x-dialog v-model="this.$store.state.app.dialogShow" >
      <div class="dialog-message">
        {{ this.$store.state.app.dialogMessage }}
      </div>
      <span class="vux-close" @click="hideDialog">知道了</span>
    </x-dialog>
  </div>
</template>
<style lang="less">
  @import "../less/bind-poster";
</style>
<script>
  // import { XInput, Group, XDialog } from 'vux'
  import XInput from 'vux/src/components/x-input'
  import Group from 'vux/src/components/group'
  import XDialog from 'vux/src/components/x-dialog'
  import Selector from 'vux/src/components/selector'
  import Divider from 'vux/src/components/divider'
  import {Checker, CheckerItem} from 'vux/src/components/checker'

  import { mapActions, mapState } from 'vuex'
  import { showDialog, hideDialog } from '../lib/dialog'

  export default {
    data () {
      return {
        poster: {
          poster_name: '',
          poster_id: '',
          type: 0
        },
        type: 0, // 0 现场扫码 1邀请码营销
        isTeam: '0',
        errors: {},
        isHandled: false,
        redirect: false
      }
    },
    mounted () {
      this.initBindButton()
      this.callJsApi('biz.navigation.setTitle', { title: '绑定' })
      if (this.$route.query.type) {
        this.type = this.$route.query.type
        this.poster.type = this.type
      }
    },

    components: {
      XInput,
      Group,
      XDialog,
      Selector,
      Divider,
      Checker,
      CheckerItem
    },
    watch: {
      isTeam (value) {
        if (value === '0' && typeof this.poster.team_id !== 'undefined' && this.poster.team_id) {
          delete this.poster.team_id
        }
      }
    },
    computed: {
      ...mapState({
        myTeamList: state => {
          // state.app.user.my_team_list
          const myTeamList = state.app.user.my_team_list
          const teamOptions = []
          for (const teamId in myTeamList) {
            const teamName = myTeamList[teamId]
            teamOptions.push({
              key: teamId,
              value: teamName
            })
          }
          return teamOptions
        },
        loginUser: state => state.app.user
      })
    },
    methods: {
      hideDialog () {
        hideDialog()
        if (this.redirect === true) {
          this.$router.push({name: 'scan-code-config', query: { type: this.type }})
        }
      },
      isValid () {
        if (this.isHandled === false) return true

        let isValid = true
        let errors = Object.assign({}, this.errors)
        if (/\d+/.test(this.poster.poster_id) === false) {
          errors.poster_id = '海报ID必须为数字'
          isValid = false
        } else if (errors.poster_id) {
          isValid = true
          delete errors.poster_id
        }

        if (!this.poster.poster_name) {
          errors.poster_name = '必须填写海报名称'
          isValid = false
        } else if (errors.poster_name) {
          isValid = true
          delete errors.poster_name
        }
        this.errors = errors
        console.log(isValid, JSON.stringify(errors))
        return isValid
      },
      saveBindPoster (callback) {
        this.isHandled = true
        if (this.isValid() === true) {
          this.$vux.loading.show({text: '提交中...'})
          this.bindPoster(this.poster).then((response) => {
            this.$vux.loading.hide()
            if (response.data.errcode === 0) {
              showDialog('绑定成功!')
              this.redirect = true
            } else {
              typeof callback === 'function' && callback()
              showDialog(response.data.errmsg)
            }
            setTimeout(() => { hideDialog() }, 4000)
          }).catch((err) => {
            typeof callback === 'function' && callback()
            showDialog('系统出错...请联系管理员')
            setTimeout(() => { hideDialog() }, 4000)
            console.log(err)
          })
        }
      },
      initBindButton () {
        let options = {
          textColor: '#0089cd',
          items: [
            {
              'id': 'save_bind', // 字符串
              'text': '保存'
            }
          ]
        }
        // let target = {path: 'edit-task', query: {type: 'add'}}
        this.callJsApi('biz.navigation.setMenu', options)
          .then((data) => {
            if (data.id === 'save_bind') {
              this.saveBindPoster(() => {
                this.initBindButton()
              })
            }
            // this.$router.push(target)
          })
      },
      ...mapActions({
        bindPoster: 'bindPoster'
      })
    }
  }
</script>
